<template>
  <div class="clearfix">
    <a-upload
      :file-list="fakeValue"
      :action="url"
      list-type="picture-card"
      v-bind="$attrs"
      :disabled="disabled"
      :headers="headers"
      @preview="handlePreview"
      @change="onChange"
    >
      <div v-if="max == -1 || fakeValue.length < max" class="img-upload">
        <s-icon v-if="!disabled" type="plus-outlined" style="width: 100%; height: 100%" />
      </div>
    </a-upload>
    <s-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </s-modal>
  </div>
</template>
<script>
import { v4 } from 'uuid'
const BASIC_URL = import.meta.env.VITE_API_PATH
import { ACCESS_TOKEN } from '@/store/mutation-types'
import ls from '@/utils/Storage'
function parseFile(fileList, successCode, prefix) {
  const array = []
  if (fileList) {
    fileList.forEach((item) => {
      if (item.status == 'done') {
        if (item.response) {
          if (item.response.code == successCode) {
            array.push(prefix + item.response.data)
          }
        } else {
          array.push(item.url)
        }
      }
    })
    return array.toString()
  }
}
export default {
  // 继承
  name: 'SImg',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      default: BASIC_URL + '/file/upload'
    },
    max: {
      type: Number,
      default: -1
    },
    modelValue: {
      type: String,
      required: false
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return {
      fakeValue: [],
      loading: true,
      previewVisible: false,
      previewImage: undefined,
      headers: {}
    }
  },
  watch: {
    modelValue(val) {
      this.initValue(val)
    }
  },
  created() {
    const token = ls.get(ACCESS_TOKEN)
    const tokenKey = import.meta.env.VITE_TOKEN_KEY
    this.headers[tokenKey] = token
    const val = this.modelValue
    this.fakeValue = []
    if (val) {
      const array = val.split(',')
      array.forEach((item) => {
        this.fakeValue.push({ status: 'done', url: item, uid: v4(), name: item })
      })
    }
  },
  methods: {
    initValue(val) {
      const newArray = []
      if (this.fakeValue) {
        this.fakeValue.forEach((item) => {
          if (item.status === 'uploading') {
            newArray.push(item)
          }
        })
      }
      this.fakeValue = newArray
      if (val) {
        const array = val.split(',')
        array.forEach((item) => {
          this.fakeValue.push({ status: 'done', url: item, uid: v4(), name: item })
        })
      }
    },
    handlePreview(file) {
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    triggerChange(changedValue) {
      this.$emit('change', changedValue)
    },
    onChange(obj) {
      const fileList = obj.fileList
      const newArray = []
      if (fileList) {
        fileList.forEach((item) => {
          if (
            item.status == 'done' &&
            (!item.response || (item.response && item.response.code == this.CODES.SUCCESS))
          ) {
            if (!item.url) {
              item.url = BASIC_URL + '/file/downLoad/' + item.response.data
            }
            newArray.push(item)
          }
          if (item.status == 'uploading') {
            newArray.push(item)
          }
        })
      }
      this.fakeValue = newArray
      const images = parseFile(obj.fileList, this.CODES.SUCCESS, BASIC_URL + '/file/downLoad/')
      if (!this.$attrs.hasOwnProperty('modelValue')) {
        this.initValue(images)
      }
      this.$emit('update:modelValue', images)
      this.$emit('change', images)
    }
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.img-upload:deep(svg) {
  font-size: 45px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
